package com.fin.zw.intelligentbot.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fin.zw.intelligentbot.entity.WebSocketMessage;
import com.fin.zw.intelligentbot.model.request.SendMsgModel;
import com.fin.zw.intelligentbot.model.request.WebSocketMessageModel;
import com.fin.zw.intelligentbot.model.response.WebSocketMessageResponse;
import com.fin.zw.intelligentbot.repository.WebSocketMessageRepository;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("webSocketService")
public class WebSocketService {
    @Autowired
    private FanoutExchange fanoutExchange;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WebSocketMessageRepository webSocketMessageRepository;


    /**
     * 发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessage(String userName, WebSocketMessageModel message) {
        ObjectMapper mapper = new ObjectMapper();
        WebSocketMessageResponse response = new WebSocketMessageResponse();
        BeanUtils.copyProperties(message, response);
        SendMsgModel sendMsgModel = new SendMsgModel();
        sendMsgModel.setMessageType(message.getMessageDataType());
        sendMsgModel.setData(response);
        String messageString = null;
        try {
            messageString = mapper.writeValueAsString(sendMsgModel);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        rabbitTemplate.convertAndSend(fanoutExchange.getName(), userName, messageString);
//        rabbitTemplate.convertAndSend("task", messageString);
        //提醒类消息
        WebSocketMessage webSocketMessage = new WebSocketMessage();
        BeanUtils.copyProperties(message, webSocketMessage);
        webSocketMessage.setUserName(userName);

        webSocketMessageRepository.save(webSocketMessage);

    }


}
